package com.absorbx.commons;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.View;

import flexjson.JSONSerializer;

public class JsonView implements View {

	// disable deep serialize by default
	private boolean deepSerialize = false;
	private String rootName;

	private JSONSerializer jsonSerializer = new JSONSerializer();

	public JsonView() {
	}

	public JsonView(String rootName, boolean deepSerizlize) {

		this.deepSerialize = deepSerizlize;

		this.rootName = rootName;
	}

	public String getContentType() {
		return "text/html; charset=UTF-8";
	}

	@SuppressWarnings("unchecked")
	public void render(Map model, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String jsonString = null;
		jsonSerializer.exclude("*.class");
		// deep serialize if sepecified.
		// Collections are serialized in full including the shallow copy of the
		// objects they contain.
		if (this.deepSerialize) {

			if (rootName != null) {
				jsonString = jsonSerializer.deepSerialize(rootName, model);
			} else {
				jsonString = jsonSerializer.deepSerialize(model);
			}

		} else {
			if (rootName != null) {
				jsonString = jsonSerializer.serialize(rootName, model);
			} else {
				jsonString = jsonSerializer.serialize(model);
			}
		}

		response.getWriter().write(jsonString);

	}

	public void include(String... fields) {
		jsonSerializer.include(fields);
	}

	public void exclude(String... fields) {
		jsonSerializer.exclude(fields);
	}

	public void setDeepSerialize(boolean deepSerialize) {
		this.deepSerialize = deepSerialize;
	}

	public void setRootName(String rootName) {
		this.rootName = rootName;
	}

}
